<template>
	<view id="nearby" class="section section-big nearby">
		<view class="title">附近低功耗蓝牙设备</view>
		<view class="filters"></view>
		<view class="shop" v-for="item in btDevices" :key="item.devId">
			<div class="dev" style="flex-direction:row;" @click="fun(item)">
				<div class="name">
					{{item.name}}
					<view class="devId">
						DevId:{{item.devId}}
					</view>
				</div>
				<div class="rssi" style="vertical-align:middle">
					<image :src="item.img" />
					{{item.rssi}}
				</div>
			</div>
		</view>
	</view>
</template>

<script>
	const app = getApp()

	export default {
		data() {
			return {
				filterId: 1,
				btDevices: app.globalData.btDevices
			}
		},

		methods: {
			fun(item) {
				let devId = JSON.stringify([item])
				this.$store.dispatch('setDevId', devId).then(() => {
					uni.navigateBack({
						delta: 1
					})
					uni.showToast({
						title: '已选择蓝牙设备'
					})
				})
			}
		},

		onLoad: function() {
			var launchToastDuration;
			if (app.globalData.platform == 'ios') {
				launchToastDuration = 1500
			} else {
				launchToastDuration = 2500
			}
			uni.showToast({
				title: 'QR-Printer',
				icon: 'loading',
				image: '/static/imgs/qr/750x750.png'
			})
		},

		onShow: function() {
			let that = this;
			if (app.globalData.platform == 'ios') {
				console.log('ios bt')
			} else {
				console.log('android bt')
			}

			uni.openBluetoothAdapter({ // 初始化蓝牙模块
				success: function(res) {
					console.log(res)
					uni.startBluetoothDevicesDiscovery({ // 开始搜寻附近的蓝牙外围设备
						success: function(res) {
							console.log(res)
						}
					})
				},
				fail: function(err) {
					if (err.errCode === 10001)
						uni.showToast({
							title: '设备蓝牙未开启',
							icon: 'none'
						})
				}
			})

			uni.onBluetoothDeviceFound(function(devices) { // 监听寻找到新设备的事件
				uni.getBluetoothDevices({ // 获取在蓝牙模块生效期间所有已发现的蓝牙设备
					success: function(res) {
						var ln = 0;
						console.log(res, that.btDevices.length)
						if (that.btDevices.length != null)
							ln = that.btDevices.length
						for (var i = ln; i < res.devices.length; ++i) {
							var rssi_level_img;
							if (res.devices[i].RSSI > 0 || res.devices[i].name == '' || res.devices[i].name == '未知设备') {
								continue;
							}
							if (res.devices[i].RSSI > -40) {
								rssi_level_img = '/static/imgs/scan/5.png'
							} else if (res.devices[i].RSSI > -50) {
								rssi_level_img = '/static/imgs/scan/4.png'
							} else if (res.devices[i].RSSI > -60) {
								rssi_level_img = '/static/imgs/scan/3.png'
							} else if (res.devices[i].RSSI > -70) {
								rssi_level_img = '/static/imgs/scan/2.png'
							} else {
								rssi_level_img = '/static/imgs/scan/1.png'
							}
							var newBtDevice = [{
								rssi: res.devices[i].RSSI,
								name: res.devices[i].name,
								devId: res.devices[i].deviceId,
								img: rssi_level_img,
							}];

							// dump redundant device
							for (var k = 0; k < that.btDevices.length; ++k) {
								//console.log('new ',res.devices[i].deviceId,'old',that.btDevices[k].devId)
								if (res.devices[i].deviceId == that.btDevices[k].devId) {
									//console.log('dump',k,that.btDevices[k].devId)
									that.btDevices.splice(k, 1);
									break;
								}
							}
							that.btDevices = that.btDevices.concat(newBtDevice)
						}

						app.globalData.btDevices = that.btDevices
					}
				})
			})
		},

		onHide: function() {
			var that = this
			uni.stopBluetoothDevicesDiscovery({
				success: function(res) {
					console.log(res)
				}
			})
		},

		onPullDownRefresh: function() { // 下拉清空记录，并重新搜索
			console.log('onPullDownRefresh')
			var that = this
			uni.stopPullDownRefresh()
			uni.stopBluetoothDevicesDiscovery({
				success: function(res) {
					console.log(res)
					uni.closeBluetoothAdapter({
						success: function(res) {
							console.log(res)
							var num = that.btDevices.length
							that.btDevices.splice(0, num)
							uni.openBluetoothAdapter({
								success: function(res) {
									console.log(res)
									uni.startBluetoothDevicesDiscovery({
										//services: ['FFF0'],
										success: function(res) {
											console.log(res)
										}
									})
								},
								fail: function(err) {
									console.log(err)
									if (err.errCode === 10001)
										uni.showToast({
											title: '设备蓝牙未开启',
											icon: 'none'
										})
								}
							})
						}
					})
				}
			})
		},

		onScroll: function(e) {
			if (e.detail.scrollTop > 100 && !this.scrollDown) {
				console.log(true)
				this.scrollDown = true
			} else if (e.detail.scrollTop < 100 && this.scrollDown) {
				console.log(false)
				this.scrollDown = false
			}
		},

		tapFilter: function(e) {
			switch (e.target.dataset.id) {
				case '2':
					this.btDevices.sort(function(a, b) {
						return b.rssi - a.rssi;
					});
					break;
			}
			this.filterId = e.target.dataset.id;
			this.btDevices = this.btDevices;
		}
	}
</script>

<style lang="scss">
	@import url('./index.scss');
</style>
